<?php

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class helper_token {
	/*
	 * $Section = 是否将密文分段 1=是 0=否
	 *
	 */
	public static function encode($KEY,$data,$Section=0){ 
	
		$KEY = md5(getglobal('authkey').$KEY);//将密钥与站点密钥组合生成新密钥 md5 32位小
		if($data && is_array($data)){
			foreach($data as $key => $value){
				$data[$key] = urlencode($value);
			}
			$data = implode("\t",$data);
		}
		$data = urlencode(authcode($data,'ENCODE',$KEY));
		
		if($Section){
			$mid = ceil(strlen($data) /2);
			return array($data,substr($data,0,$mid),substr($data,$mid));//将密文分成三段 第一段=原始密文 第二段=上半段 第三段=下半段
		}else{
			return $data;
		}
	}
	public static function decode($KEY,$token){
		
		$KEY = md5(getglobal('authkey').$KEY);//将密钥与站点密钥组合生成新密钥 md5 32位小
		$token = authcode(urldecode($token),'DECODE',$KEY);
		if($token && strpos($token,"\t")){
			$return = array();
			$token = explode("\t",$token);
			foreach($token as $k => $value){
				$return[] = urldecode($value);
			}
			return $return;
		}
		return $token;
	}
	public static function ckeck($key,$token='',$data=array()){
		$token = $this->decode($token,$key);
		if($data && is_array($data) && $token && is_array($token)){
			$sta = 0;
			foreach($token as $key => $value){
				if($data[$key] == $value){
					$sta ++;
				}
			}
			if($sta == count($data) && $sta == count($token)){
				return true;
			}
		}
		return false;
	}
}

?>